import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
  
const cartList = ref([])
const addItem =(playload)=>{
    const index = cartList.value.findIndex(item=>item.id == playload.id)
    if(index > -1)
    {
        return cartList.value[index].count++
    }else{
       return   cartList.value.push({
            ...playload,
            count:1,
            checked:false
        })
    }
}

   const delItem=(id)=>{
      cartList.value =cartList.value.filter(item=>item.id !=id)
   }

   const updateCount=(id,count)=>{
         cartList.value.find(item=>item.id==id).count=count
   }

   const totalCount =computed(()=>{
       let res =0 
       cartList.value.forEach(item=>{
          res+=item.count
       })
       return res
   })
   const totalPrice =computed(()=>{
       let res =0 
       cartList.value.forEach(item=>{
        if(item.checked==true)
        {
            res+=item.count*item.price
        }
       
       })
       return res
   })
  return { cartList,addItem,delItem,totalCount,totalPrice,updateCount}
},{
    persist:true
})